package com.hw.webflux.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsConfigurationSource;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;

/**
 * @program: spring-webflux
 * @description: 跨域配置（通过filter实现跨域）
 * @author: hewei
 * @date: 2021-11-04 17:26
 **/
@Configuration
public class CorsConfig {

    /*跨域配置*/
    @Bean
    public CorsConfiguration corsConfiguration(){
        CorsConfiguration config = new CorsConfiguration();

        config.setAllowCredentials(true);
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        return config;
    }

    /*支持跨域的请求路径*/
    @Bean
    public UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource(CorsConfiguration corsConfiguration){
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", corsConfiguration);
        return source;
    }

    /*跨域拦截器*/
    @Bean
    public CorsWebFilter corsWebFilter(CorsConfigurationSource configSource){
        return new CorsWebFilter(configSource);
    }
}
